import re

from django.conf import settings
from django.core import signing
from django.core.signing import SignatureExpired
from django.urls import reverse
from django.views.generic.base import View
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render

from apps.goods.models import GoodsSKUBean
from apps.user.models import UserBean, AddressBean
from celery_task.tasks import send_Email

# 类视图使请求方式更加规范
class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 获取用户输入值
        # 用户名
        username = request.POST.get("user_name")
        # 密码
        password = request.POST.get("pwd")
        # 确认密码
        repassword = request.POST.get("cpwd")
        # 邮箱
        email = request.POST.get("email")
        # 是否确认协议
        allow = request.POST.get("allow")

        # 校验数据  为什么前台已经校验过了还要校验：防止有些非法提交不经过form表单提交，通过其他方法提交
        if not all([username, password, repassword, email]):
            return render(request, 'register.html', {'errormessage': '数据不完整'})
            # 校验邮箱
        if not re.match(r"^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$", email):
            return render(request, "register.html", {"errormessage": "邮箱格式有误!"})
        # 密码核对
        if password != repassword:
            return render(request, "register.html", {"errormessage": "两次输入的密码不一致!"})
            # 是否同意协议
        if allow != "on":
            return render(request, "register.html", {"errormessage": "请勾选极致果蔬用户协议!"})

        try:
            user = UserBean.objects.get(username=username)
        except UserBean.DoesNotExist:
            user = None
        if user:
            return render(request, 'register.html', {'errormessage': '用户名已存在'})

        # 添加用户
        userObj = UserBean.objects.create_user(username, email, password, is_active=False)
        userSign = signing.dumps({'userid': userObj.id})

        # 发送激活邮件
        send_Email.delay(
            '极致果蔬用户激活确认',
            "",
            settings.EMAIL_FROM,
            [email],
            html_message=f'欢迎你：{username},请点击下方链接，激活账号！<br><a href="http://127.0.0.1:8000/user/email_active/{userSign}">激活</a>'
        )

        # 返回登录页面
        return render(request, 'pagenum.html',
                      {
                          'msg': f'注册成功！请前往邮箱进行激活，还有<span id="seconds">5</span>秒跳转到登录页面,点击<a href="{reverse("login")}">跳转</a>',
                          'location': f'{reverse("login")}'})
        # return HttpResponseRedirect(reverse('login'))
# 激活邮箱类视图
class EmailActiveView(View):
    def get(self, request,userSign):
        try:
            user = signing.loads(userSign, max_age=2*24*3600)
        except SignatureExpired as e:
            return HttpResponse('该激活链接已过期！请联系管理员：11111111@qq.com')

        userRes = UserBean.objects.filter(id=user.get('userid'))

        if not userRes:
            return HttpResponse('该用户不存在！返回首页！<a href="/">首页</a>')

        userRes[0].is_active = True
        userRes[0].save()
        return render(request, 'pagenum.html',
                      {'msg': f'注册成功！还有<span id="seconds">5</span>秒跳转到登录页面,点击<a href="{reverse("login")}">跳转</a>',
                            'location':f'{reverse("login")}'})
        # return HttpResponse('ok')
# 登录类视图
class LoginView(View):
    def get(self, request):
        next_url = request.GET.get('next',reverse('index'))
        username = ''
        remember = ''
        if 'username' in request.COOKIES:
            username = request.COOKIES.get('username')
            remember = 'checked'
        return render(request, 'login.html',
                      {'errormessage': username, 'checked': remember, 'next_url': next_url})

    def post(self,request):
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        remember = request.POST.get('remember')
        # 校验数据
        if not all([username, password]):
            return render(request, "login.html", {"errormessage": "输入的数据不完整!"})
        from django.contrib.auth import authenticate, login
        user = authenticate(username=username, password=password)
        content = request.session.get("username")
        print("获取session的值：",content)

        if user is not None:
            # 用户名密码正确
            # 验证是否激活
            if user.is_active:
                # 判断是否需要记住用户名
                next_url = request.GET.get('next',reverse('index'))
                response = render(request, 'pagenum.html',
                              {'msg': f'登录成功！，还有<span id="seconds">2</span>秒跳转到商品首页,'
                                      f'点击<a href="{next_url}")">跳转</a>',
                               'location': f'{next_url}'
                               })
                # 判断是否记住用户名
                if remember == 'on':
                    response.set_cookie('username', username, max_age=5 * 24 * 3600)
                else:
                    response.delete_cookie('username')
                login(request, user)
                return response
            else:
                return render(request, 'login.html', {'errormessage': '邮箱未激活！'})
        else:
            return render(request, 'login.html', {'errormessage': '用户名或者密码错误！'})
# 退出登录的类视图
class LogoutView(View):
    def get(self, request):
        from django.contrib.auth import logout
        logout(request)
        return render(request, 'pagenum.html',
                      {'msg': f'退出成功！还有<span id="seconds">3</span>秒跳转到登录页面,点击<a href="{reverse("login")}">跳转</a>',
                       'location': f'{reverse("login")}'})
# 用户中心-个人信息 类视图
class UserInfoView(View):
    def get(self, request):
        user = request.user
        try:
            default_address = AddressBean.objects.get(user=user, is_default=1, is_delete=0)
        except:
            # 不存在默认地址
            default_address = None
        # 显示用户浏览信息
        # 获取redis对象
        from django_redis import get_redis_connection
        # 获取连接对象
        conn = get_redis_connection('default')
        # 构造存储浏览记录的key
        historyKey = f'history_{user.id}'
        # 根据key获取最新的5条skuid列表
        skuids = conn.lrange(historyKey, 0, 4)
        # 根据每一个skuid查询相应的产品信息
        goodsSkuList = []
        for skuid in skuids:
            goodsSku = GoodsSKUBean.objects.get(id=skuid)
            goodsSkuList.append(goodsSku)

        return render(request, 'user_center_info.html',
                      {'page': 'info',
                       'default_address': default_address,
                       "goodsSkuList": goodsSkuList})

# 用户订单信息-全部订单 类视图
class UserOrderView(View):
    def get(self,request):
        return render(request, 'user_center_order.html',
                      {"page": "order"})

# 用户中心-收货地址 类视图
class UserAsddressView(View):
    def get(self,request):
        # 获取用户的默认地址
        user = request.user
        addresses = AddressBean.objects.filter(user=user, is_delete=0).order_by('-is_default')
        # print("获取对象", addresses)
        return render(request, 'user_center_site.html',
                      {"page": "address", 'addresses': addresses})
    def post(self,request):
        # 接收数据
        receiver = request.POST.get("receiver")
        addr = request.POST.get("address")
        post_code = request.POST.get("post_code")
        phone = request.POST.get("phone")
        # 校验数据
        if not all([receiver, addr, phone]):
            return render(request, "user_center_site.html", {"errormessage": "您填写的内容不完整."})
        if not re.match(r"^1[3|4|5|7|8][0-9]{9}$", phone):
            return render(request, "user_center_site.html", {"errormessage": "您填写的手机号码格式有误."})

        # 根据用户来查询地址
        user = request.user
        try:
            # 存在默认地址
            addressbean = AddressBean.objects.get(user=user, is_default=True)
        except Exception:
            # 不存在默认地址
            addressbean = None
        if addressbean:
            is_default = False
        else:
            is_default = True
        # 添加/提交地址
        AddressBean.objects.create(receiver=receiver,
                                   address=addr,
                                   post_code=post_code,
                                   phone_num=phone,
                                   is_default=is_default,
                                   user=user)
        return render(request, 'pagenum.html',
                      {'msg': f'添加地址成功！还有<span id="seconds">3</span>秒跳转到用户地址,'
                              f'点击<a href="{reverse("address")}">跳转</a>',
                       'location': f'{reverse("address")}'})


class UserDefaultAddrChange(View):
    def get(self, request):
        default_id = request.GET.get('default_id')
        user = request.user
        AddressBean.objects.filter(user=user, is_default=1, is_delete=0).update(is_default=0)
        AddressBean.objects.filter(user=user, id=default_id).update(is_default=1)

        return JsonResponse({
            'code':200,
            'msg':'修改成功'
        })






















